import { Body, Controller, Get, Post, Query, Req } from '@nestjs/common';
import { BaseController } from '../base/base.controller';
import { DbService } from '@app/db';
import { PlatformDailyIncome } from '@app/db/entities/PlatformDailyIncome';
import { FindOptionsWhere, MoreThanOrEqual, LessThanOrEqual, And } from 'typeorm';
import { DailyPageDto } from './dto';
import { PlatformService } from './platform.service';

@Controller('platform')
export class PlatformController extends BaseController{
    constructor(
        private readonly db:DbService,
        private readonly service:PlatformService,
    ) {
        super()
    }
    @Post('daily/page')
    async incomeLogPage(@Query() dto:DailyPageDto, @Req() { member }) {
        let result:PaginationResult<PlatformDailyIncome> = {
            total : 0,
            rows : []
        }

        let where:FindOptionsWhere<PlatformDailyIncome> = {

        }

        if(dto.startTime || dto.endTime) {
            if(dto.startTime == dto.endTime) {
                where.date = dto.startTime
            }else {
                const dates:any = []
                if(dto.startTime) {
                    dates.push(MoreThanOrEqual(dto.startTime))
                }

                if(dto.endTime) {
                    dates.push(LessThanOrEqual(dto.endTime))
                }

                where.date = And(...dates)
            }
        }

        

        result.total = await this.db.platformDailyIncome.count(where)

        if(result.total > 0) {
            result.rows = await this.db.platformDailyIncome.pagination(dto.pageNo, dto.pageSize, where, null, {id : 'DESC'})
        }
        

        return this.successRes(result)

    }

    @Get('statistics')
    async statistics() {
        const data = await this.service.statistics()
        return this.successRes(data)
    }


    @Post('daily/rang/amount/chargeCount')
    async incomeChart(@Body() dates:{startDate:number, endDate:number}) {
        let where:FindOptionsWhere<PlatformDailyIncome> = {

        }

        if(dates.startDate == dates.endDate) {
            where.date = dates.startDate
        }else {
            where.date = And(MoreThanOrEqual(dates.startDate), LessThanOrEqual(dates.endDate))
        }

        const rows = await this.db.platformDailyIncome.find(where, ['amount', 'chargeOrderCount', 'date'])


        return this.successRes(rows)
    }
}
